package com.sdgakj.service.news;

import com.google.common.collect.Maps;
import com.sdgakj.dto.FeedCommentDTO;
import com.sdgakj.dto.base.ResCode;
import com.sdgakj.entity.Feed;
import com.sdgakj.entity.FeedComment;
import com.sdgakj.entity.News;
import com.sdgakj.entity.User;
import com.sdgakj.enums.EnumIsDelete;
import com.sdgakj.repository.NewsDao;
import com.sdgakj.repository.UserDao;
import com.sdgakj.service.ServiceException;
import com.sdgakj.service.user.UserService;
import org.apache.commons.lang.exception.Nestable;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;

import java.util.List;
import java.util.Map;


@Component
@Transactional
public class NewsService {
	
	@Autowired
	private NewsDao newsDao;

	@Autowired
	private UserDao userDao;
	@Autowired
	private UserService userService;

	private static Logger logger =LoggerFactory.getLogger(NewsService.class);

	/**
	 * 查询家族列表
	 * @param searchParams
	 * @param pageNumber
	 * @param pageSize
	 * @param sortType
     * @return
     */
	public Page<News> getNews(Map<String,Object> searchParams, int pageNumber, int pageSize,
								   String sortType){
		PageRequest pageRequest =buildPageRequest(pageNumber,pageSize,sortType);
		Specification<News> spec =buildSpecification(searchParams);

        Page<News> families = newsDao.findAll(spec, pageRequest);
	/*	Sort sort=buildSortRequest("createTime",sortType);
		List<News> list=newsDao.findAll(spec,sort);
		for (News n:list
			 ) {
			System.out.println(n.getCreatetime());
		}
*/

        return families;
	}

	/**
	 * 创建排序.
	 */
	private Sort buildSortRequest(String sortName,String sortType) {
		Sort sort = null;
		if ("auto".equals(sortType)) {
			sort = new Sort(Direction.DESC, "id");
		}else if("desc".equals(sortType)){
			sort = new Sort(Direction.DESC, sortName);
		}else{
			sort = new Sort(Direction.ASC, sortName);
		}
		return sort;
	}
	
	/**
	 * 创建分页请求.
	 */
	private PageRequest buildPageRequest(int pageNumber, int pagzSize, String sortType) {
		Sort sort = null;
		if ("auto".equals(sortType)) {
			sort = new Sort(Direction.DESC, "id");
		}

		return new PageRequest(pageNumber - 1, pagzSize, sort);
	}
	
	/**
	 * 创建动态查询条件组合.
	 */
	private Specification<News> buildSpecification(Map<String, Object> searchParams) {
		Map<String, SearchFilter> filters = SearchFilter.parse(searchParams);
		//  根据用户类型设置查询条件
//		filters.put("user.type", new SearchFilter("user.type", Operator.EQ, EnumUserType.CUSTOMOR.getCode()));
		Specification<News> spec = DynamicSpecifications.bySearchFilter(filters.values(),News.class);
		return spec;
	}

	public News getNewsById(Long id) {
		return newsDao.findOne(id);
	}

	public News getNewsByNewsName(String fName) {
		Map<String, SearchFilter> filters = Maps.newHashMap();
		if(StringUtils.isNotBlank(fName)){
			filters.put("fName", new SearchFilter("fName", SearchFilter.Operator.EQ, fName)); //父节点
		}
		Specification<News> spec = DynamicSpecifications.bySearchFilter(filters.values(), News.class);
		return newsDao.findOne(spec);
	}

	public News updateNews(News entity) {
		return newsDao.save(entity);

	}

	public News saveNews(News News) {
		return newsDao.save(News);
	}
	public void deleteNews(Long id) {
		newsDao.delete(id);
	}

	/**
	 * 创建新闻评论
	 *
	 * @param customerId
	 * @param replyCustomerId
	 * @param id
	 * @param content
	 * @return
	 */
	public FeedCommentDTO createComment(Long customerId,
										Long replyCustomerId, Long id, String content){
		FeedComment comment = new FeedComment();
		User customer =userService.getUserById(customerId);
		if(customer == null || EnumIsDelete.DELETED.getCode().equals(customer.getDeltag())) {
			throw new ServiceException(ResCode.COMMON_CUSTOMER_NO_PERMISSION);
		}
		comment.setUserId(customerId);
		if(replyCustomerId == null) {
			comment.setReplyUserid(null);
		} else {
			User replyCustomer =userService.getUserById(customerId);
			if(replyCustomer == null || EnumIsDelete.DELETED.getCode().equals(replyCustomer.getDeltag())) {
				throw new ServiceException(ResCode.FEED_REPLY_CUSTOMER_NO_PERMISSION);
			}
			comment.setReplyUserid(customerId);
		}

		News news=newsDao.findOne(id);
		if(news == null || EnumIsDelete.DELETED.getCode().equals(news.getDeltag())) {
			//提示已经删除
			throw new ServiceException(ResCode.FEED_NOT_EXIST);
		}
		/*else{
			//如果自己评论 则不发消息
			if(news.getUserId()==customerId){

			}
		}*/
		//把新闻的信息填充到feed实体类
		Feed feed=new Feed();
		feed.setUserId(news.getUserId());
		feed.setfId(1L);
		feed.setDeltag("0");
		feed.setCreateDate(news.getCreatetime());
		feed.setUpdateDate(news.getCreatetime());
		feed.setPics(news.getImgUrl());

		return  null;
	}
}
